<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px" @submit.prevent>
      <el-form-item label="储位编码" prop="storageId">
        <el-input
          v-model.trim="queryParams.storageId"
          placeholder="储位编码"
          clearable
          @keyup.enter="handleQuery"
          style="width: 175px"
        />
      </el-form-item>
      <el-form-item label="储位类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择储位类型"
          clearable
          style="width: 175px"
          @change="handleQuery"
        >
          <el-option
            v-for="item in storage_type"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="存储状态" prop="status">
        <el-select v-model="queryParams.status" clearable style="width: 175px;" placeholder="请选择存储状态"  @change="handleQuery">
          <el-option
            v-for="item in storage_status"
            :key="item.value"
            :label="item.label"
            :value="Number(item.value)"
          />
        </el-select>
      </el-form-item>
    <!-- 在模板中找到原有的所属厂区输入框，替换为 -->
    <el-form-item label="所属厂区" prop="warehouseZonesName">
      <el-select
        v-model.trim="queryParams.warehouseZonesName"
        placeholder="请选择所属厂区"
        clearable
        style="width: 175px"
        @change="handleQuery"
      >
        <el-option
          v-for="zone in zoneNames"
          :key="zone"
          :label="zone"
          :value="zone"
        />
      </el-select>
    </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:storagePosition:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:storagePosition:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:storagePosition:remove']"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:storagePosition:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Download"
          @click="downloadTemplate"
        >下载导入模板</el-button>
      </el-col>
      <el-col :span="1.5">
        <MyUpload
          buttonName="导入大厅储位" 
          url="/api/storagePosition/import"
          @success="handleUploadSuccess"
          @warning="handleUploadWarning"
          />
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Grid"
          @click="handleZoneManagement"
        >厂区划分</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <TableScrollContainer :topHeight="220">
      <template #default="{ tableHeight }">
        <el-table v-loading="loading" :data="storageList" @selection-change="handleSelectionChange" :height="tableHeight" border>
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="储位编码" align="center" prop="storageId" />
          <el-table-column label="料箱编号" align="center" prop="containerId" />
          <el-table-column label="储位类型" align="center" prop="type">
            <template #default="scope">
              <dict-tag :options="storage_type" :value="scope.row.type"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="储位高度类型" align="center" prop="boxHeightType">
            <template #default="scope">
              <dict-tag :options="box_height_type" :value="scope.row.boxHeightType"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="排号" align="center" prop="rowNum" />
          <el-table-column label="列号" align="center" prop="colNum" />
          <el-table-column label="层号" align="center" prop="floorNum" />
          <el-table-column label="所属厂区" align="center" prop="warehouseZonesName" />
          <el-table-column label="存储状态" align="center" prop="status">
            <template #default="scope">
              <dict-tag :options="storage_status" :value="scope.row.status"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="锁库状态" align="center" prop="lockStatus">
            <template #default="scope">
              <dict-tag :options="lock_status" :value="scope.row.lockStatus"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="禁用状态" align="center" prop="disableStatus">
            <template #default="scope">
              <dict-tag :options="disable_status" :value="scope.row.disableStatus"></dict-tag>
            </template>
          </el-table-column>
          <el-table-column label="禁用备注" align="center" prop="disableRemark">
            <template #default="scope">
              {{ scope.row.disableStatus === 1 ? scope.row.disableRemark : '' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="285" fixed="right">
            <template #default="scope">
              <el-button type="success" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:storagePosition:edit']">修改</el-button>
              <el-button type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:storagePosition:remove']">删除</el-button>
              <el-button
                type="warning" 
                :icon="scope.row.disableStatus === 1 ? 'Check' : 'Close'" 
                @click="handleDisable(scope.row)"
              >
                {{ scope.row.disableStatus === 1 ? '启用' : '禁用' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page-sizes="[10, 30, 50, 100]"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </template>
    </TableScrollContainer>

    <!-- 添加或修改储位对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" :close-on-click-modal="false">
      <el-form ref="storageRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item v-if="form.storageId" label="储位编码" prop="storageId">
          <el-input v-model="form.storageId" disabled placeholder="系统自动生成" />
        </el-form-item>
        <el-form-item label="储位类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择储位类型">
            <el-option
              v-for="item in storage_type"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="储位高度类型" prop="boxHeightType">
          <!-- <el-select v-model="form.boxHeightType" placeholder="请选择箱子高度类型" @change="checkBoxHeightAndFloor">
            <el-option label="175mm（矮箱）- 只能放1-7层" value="1" />
            <el-option label="340mm（高箱）- 只能放8-9层" value="2" />
          </el-select> -->
          <el-select v-model="form.boxHeightType" placeholder="请选择">
            <el-option
              v-for="item in box_height_type"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排号" prop="rowNum">
          <el-input v-model.number="form.rowNum" placeholder="排号（1-42）" />
        </el-form-item>
        <el-form-item label="列号" prop="colNum">
          <el-input v-model.number="form.colNum" placeholder="列号（1-42）" />
        </el-form-item>
        <el-form-item label="层号" prop="floorNum">
          <el-input v-model.number="form.floorNum" placeholder="层号（1-9）" @change="checkBoxHeightAndFloor" />
        </el-form-item>
        <el-form-item label="所属厂区" prop="warehouseZonesName">
          <el-input v-model="form.warehouseZonesName" placeholder="可选，后续可通过厂区划分功能设置" />
        </el-form-item>
        <!-- <el-form-item label="容器ID" prop="containerId">
          <el-input v-model="form.containerId" placeholder="可选" />
        </el-form-item>
        <el-form-item label="x坐标" prop="xCoordinate">
          <el-input v-model="form.xCoordinate" placeholder="可选" />
        </el-form-item>
        <el-form-item label="y坐标" prop="yCoordinate">
          <el-input v-model="form.yCoordinate" placeholder="可选" />
        </el-form-item> -->
        <el-form-item v-if="form.storageId" label="存储状态" prop="status">
          <!-- <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="空闲" value="0" />
            <el-option label="占用" value="1" />
          </el-select> -->
          <el-select v-model="form.status" placeholder="请选择存储状态">
            <el-option
              v-for="item in storage_status"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.disableStatus === 1" label="禁用备注" prop="disableRemark">
          <el-input v-model="form.disableRemark" type="textarea" rows="3" placeholder="请输入禁用原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 库区划分对话框 -->
    <el-dialog title="储位所属厂区划分" v-model="zoneDialogVisible" width="500px" :before-close="zoneClose" :close-on-click-modal="false">
      <el-form ref="zoneRef" :model="zoneForm" :rules="zoneRules" label-width="120px">
        <el-form-item label="所属厂区" prop="warehouseZonesId">
          <!-- <el-input v-model="zoneForm.warehouseZonesId" placeholder="请输入要划分的库区ID" /> -->
          <el-select v-model="zoneForm.warehouseZonesId" placeholder="请选择所属厂区">
            <el-option
              v-for="item in availableList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="起始排号" prop="startRow">
          <el-input v-model.number="zoneForm.startRow" placeholder="请输入起始排号（1-42）" />
        </el-form-item>
        <el-form-item label="结束排号" prop="endRow">
          <el-input v-model.number="zoneForm.endRow" placeholder="请输入结束排号（1-42）" />
        </el-form-item>
        <el-form-item label="起始列号" prop="startCol">
          <el-input v-model.number="zoneForm.startCol" placeholder="请输入起始列号（1-42）" />
        </el-form-item>
        <el-form-item label="结束列号" prop="endCol">
          <el-input v-model.number="zoneForm.endCol" placeholder="请输入结束列号（1-42）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitZoneForm">确 定</el-button>
          <el-button @click="zoneClose">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <div class="ban-reason">
      <el-dialog
        title="请输入禁用原因"
        v-model="dialogVisible"
        width="400px"
        :close-on-click-modal="false"
        :before-close="handleClose"
       >
        <el-input v-model="reason" type="textarea" placeholder="请输入禁用原因"></el-input>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleClose">取 消</el-button>
            <el-button type="primary" :loading="btn.ban" @click="banStorage(null)">确 定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup name="storagePosition">
import { listStoragePosition, getStoragePosition, delStoragePosition, addStoragePosition, updateStoragePosition, batchSetWarehouseZones, updateStatusAPI, getAvailableListAPI } from "@/api/work/storagePosition"
// 引入获取厂区名称的API
import { getWarehouseZoneNames } from "@/api/work/warehouse"
import TableScrollContainer from '@/components/Pagetable/TableScrollContainer.vue'
const { proxy } = getCurrentInstance()
// 数据字典
const { storage_type, box_height_type, storage_status, lock_status, disable_status } = proxy.useDict(
  'storage_type', 
  'box_height_type', 
  'storage_status', 
  'lock_status', 
  'disable_status'
)

const storageList = ref([])
const open = ref(false)
const zoneDialogVisible = ref(false)
const dialogVisible = ref(false)
const reason = ref('')
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const btn = reactive({
  ban: false
})
const choosen = ref({})
// 新增：厂区列表数据
const zoneNames = ref([])

// 表单数据
const data = reactive({
  form: {},
  zoneForm: {
    warehouseZonesId: '',
    startRow: 1,
    endRow: 1,
    startCol: 1,
    endCol: 1,
    operatorId: 0 // 后续从登录信息获取
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    storageId: null,
    warehouseZonesId: null,
    containerId: null,
    type: null,
    status: null,
    disableStatus: null,
    boxHeightType: null,
    warehouseZonesName: null  // 用于搜索的厂区名称（已启用）
  },
  rules: {
    type: [
      { required: true, message: '请选择储位类型', trigger: 'blur' }
    ],
    boxHeightType: [
      { required: true, message: '请选择箱子高度类型', trigger: 'blur' }
    ],
    rowNum: [
      { required: true, message: '排号', trigger: 'blur' },
      { type: 'number', min: 1, max: 42, message: '排号必须在1-42之间', trigger: 'blur' }
    ],
    colNum: [
      { required: true, message: '列号', trigger: 'blur' },
      { type: 'number', min: 1, max: 42, message: '列号必须在1-42之间', trigger: 'blur' }
    ],
    floorNum: [
      { required: true, message: '层号', trigger: 'blur' },
      { type: 'number', min: 1, max: 9, message: '层号必须在1-9之间', trigger: 'blur' }
    ]
  },
  zoneRules: {
    warehouseZonesId: [
      { required: true, message: '选择所属厂区', trigger: 'blur' }
    ],
    startRow: [
      { required: true, message: '起始排号', trigger: 'blur' },
      { type: 'number', min: 1, max: 42, message: '起始排号必须在1-42之间', trigger: 'blur' }
    ],
    endRow: [
      { required: true, message: '结束排号', trigger: 'blur' },
      { type: 'number', min: 1, max: 42, message: '结束排号必须在1-42之间', trigger: 'blur' }
    ],
    startCol: [
      { required: true, message: '起始列号', trigger: 'blur' },
      { type: 'number', min: 1, max: 42, message: '起始列号必须在1-42之间', trigger: 'blur' }
    ],
    endCol: [
      { required: true, message: '结束列号', trigger: 'blur' },
      { type: 'number', min: 1, max: 42, message: '结束列号必须在1-42之间', trigger: 'blur' }
    ]
  }
})

const { queryParams, form, rules, zoneForm, zoneRules } = toRefs(data)

// 新增：获取厂区名称列表
const getZoneNameList = async () => {
  try {
    const response = await getWarehouseZoneNames()
    if (response.errCode === '1') {
      zoneNames.value = response.data.zoneNames
    }
  } catch (error) {
    console.error('获取厂区列表失败', error)
  }
}

const handleClose = async () => {
  dialogVisible.value = false
  reason.value = ''
  choosen.value = {}
}

const banStorage = async (val) => {
  try {
    btn.ban = true
    const res = await updateStatusAPI({
      storageId: choosen.value.storageId,
      disableStatus: val === 0 ? val : 1,
      disableRemark: reason.value
    })
    if (res.errCode === '1') {
      getList()
      proxy.$modal.msgSuccess(res.msg)
      reason.value = ''
      dialogVisible.value = false
    } else {
      proxy.$modal.msgError(res.msg)
    }
  } finally {
    btn.ban = false
  }
}

/** 查询储位列表 */
function getList() {
  loading.value = true
  listStoragePosition(queryParams.value).then(res => {
    if (res.errCode === '1') {
      storageList.value = res.data.page.records
      total.value = res.data.page.total
      loading.value = false
    }
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    storageId: null,
    warehouseZonesId: null,
    containerId: null,
    type: null,
    boxHeightType: null,
    rowNum: null,
    colNum: null,
    floorNum: null,
    xCoordinate: null,
    yCoordinate: null,
    status: 0,
    lockStatus: 0,
    disableStatus: 0,
    disableRemark: null
  }
  proxy.resetForm("storageRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  // 重置时清空厂区选择
  queryParams.value.warehouseZonesName = null
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.storageId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加储位"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row ? row.storageId : ids.value[0]
  getStoragePosition(_id).then(res => {
    if (res.errCode === '1') {
      form.value = res.data.storagePosition
      open.value = true
      title.value = "修改储位"
    }
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["storageRef"].validate(valid => {
    if (valid) {
      // 检查箱子高度类型和楼层的匹配关系
      if (!checkBoxHeightAndFloor()) {
        return
      }
      
      if (form.value.storageId != null) {
        updateStoragePosition(form.value).then(res => {
          if (res.errCode === '1') {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError(res.msg)
          }
        })
      } else {
        addStoragePosition(form.value).then(res => {
          if (res.errCode === '1') {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError(res.msg)
          }
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.storageId ? row.storageId : ids.value
  proxy.$modal.confirm('是否确认删除储位编码为"' +  _ids  + '"的数据项？').then(function() {
    return delStoragePosition(_ids)
  }).then(res => {
    if (res.errCode === '1') {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    } else {
      proxy.$modal.msgError(res.msg)
    }
  }).catch(() => {})
}

/** 禁用/启用操作 */
function handleDisable(row) {
  if (row.disableStatus === 0) {
    // 禁用
    choosen.value = row
    dialogVisible.value = true
  } else {
    // 启用
    choosen.value = row
    banStorage(0)
  }
  // const action = row.disableStatus === 1 ? "启用" : "禁用"
  // const newStatus = row.disableStatus === 1 ? 0 : 1
  // const content = newStatus === 1 ? "禁用原因" : ""
  
  // proxy.$prompt(content, `确认${action}`, {
  //   confirmButtonText: '确定',
  //   cancelButtonText: '取消',
  //   inputVisible: newStatus === 1,
  //   inputPlaceholder: '禁用原因'
  // }).then(({ value }) => {
  //   return proxy.request({
  //     url: `/api/storagePosition/updateDisableStatus`,
  //     method: 'post',
  //     params: {
  //       storageId: row.storageId,
  //       disableStatus: newStatus,
  //       disableRemark: newStatus === 1 ? value : '',
  //       operatorId: proxy.$store.getters.userId
  //     }
  //   })
  // }).then(res => {
  //   if (res.errCode === '1') {
  //     proxy.$modal.msgSuccess(`${action}成功`)
  //     getList()
  //   } else {
  //     proxy.$modal.msgError(res.msg)
  //   }
  // }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('/api/storagePosition/export', {
    ...queryParams.value
  }, `储位数据_${new Date().getTime()}.xlsx`)
}

const availableList = ref([])
const getAvailableList = async() => {
  const res = await getAvailableListAPI()
  if (res.errCode === '1') {
    availableList.value = res.data.availableZones.map(item => {
      return {
        value: item.warehouseZonesId,
        label: item.warehouseZonesName
      }
    })
  }
}

/** 库区划分按钮操作 */
function handleZoneManagement() {
  getAvailableList()
  zoneDialogVisible.value = true
}

const zoneClose = () => {
  zoneDialogVisible.value = false
  // resetZoneForm()
  proxy.resetForm("zoneRef")
}

/** 提交库区划分表单 */
function submitZoneForm() {
  proxy.$refs["zoneRef"].validate(valid => {
    if (valid) {
      // 检查起始值是否小于等于结束值
      if (zoneForm.value.startRow > zoneForm.value.endRow) {
        proxy.$modal.msgError("起始排号不能大于结束排号")
        return
      }
      if (zoneForm.value.startCol > zoneForm.value.endCol) {
        proxy.$modal.msgError("起始列号不能大于结束列号")
        return
      }
      
      batchSetWarehouseZones(zoneForm.value).then(res => {
        if (res.errCode === '1') {
          proxy.$modal.msgSuccess(`库区划分成功，共更新${res.data.affectedRows}个储位`)
          zoneDialogVisible.value = false
          getList()
        } else {
          proxy.$modal.msgError(res.msg)
        }
      })
    }
  })
}

/** 检查箱子高度类型和楼层的匹配关系 */
function checkBoxHeightAndFloor() {
  if (!form.value.boxHeightType || !form.value.floorNum) {
    return true
  }
  
  // 1-175mm（矮箱子）只能放在1-7层
  // 2-340mm（高箱子）只能放在8-9层
  if (form.value.boxHeightType === 1 && (form.value.floorNum < 1 || form.value.floorNum > 7)) {
    proxy.$modal.msgError("矮箱子(175mm)只能放置在1-7层")
    return false
  }
  
  if (form.value.boxHeightType === 2 && (form.value.floorNum < 8 || form.value.floorNum > 9)) {
    proxy.$modal.msgError("高箱子(340mm)只能放置在8-9层")
    return false
  }
  
  return true
}

// 下载模板
const downloadTemplate = async() => {
  proxy.download('/api/storagePosition/downloadTemplate', {}, `储位导入模板_${new Date().getTime()}.xlsx`)
}

// 上传成功后的回调
const handleUploadSuccess = (res) => {
  getList()
  proxy.$modal.msgSuccess("导入成功")
}

// 部分成功回调
const handleUploadWarning = (res) => {
  getList()
  proxy.$modal.msgWarning(res.msg)
}

// 初始化查询和获取厂区列表
getZoneNameList()
getList()

// 注册组件
defineProps({})
defineEmits({})
</script>
<style lang="scss" scoped>
.ban-reason {
  :deep(.el-dialog) {
  transform: none;
  left: 0;
  position: relative;
  margin: 300px auto !important;
  }
}
</style>